// Created by liusc on 2020/8/5-9:24.
import { getDict } from "~/utils";
import uploadMedia from "@/components/upload-media";
import {
	updateBudgetParameter2,
	getObj,
	getEditHis,
	getParameterItem2
} from "@/views/wy-budget/api/budgetparameter.js";
import {
	getFiles,
	checkFiles,
	delFiles
} from "@/views/wy-budget/api/fileoperation.js";
import Budget from "@/assets/vue-mixin/budget";
import fileUpload from "@/views/wy-budget/components/fileUpload";
import { priceValidate } from "@/utils/validate";

export default {
	name: "apply_edit",
	mixins: [Budget],
	components: { uploadMedia, fileUpload },

	data() {
		var doubleValidate = (rule, value, callback) => {
			let reg = /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/;
			let lable = rule.message;
			if (!reg.test(value)) {
				return callback(new Error("数值格式错误"));
			} else {
				callback();
			}
		};

		return {
			//数据主键ID
			parameterId: "",
			// 文件ID
			fileId: "",
			applyFileId: "",
			applyFileId2: "",
			amendFileId: "",
			amendFileId2: "",
			isShow: false,
			fileUploadUrl: "/admin/sys-file/upLodeFileEdit",
			uploadFileList: [],
			fileList: [],
			modelType: "budgetApply",
			isEdit: true,
			busId: "",
			busId2: "",
			busId3: "",
			isBusFlag: false,
			isBusFlag2: false,
			isBusFlag3: false,
			editList: [],

			form: {
				applyData: {
					parameterId: "",
					applyId: "",
					budgetId: "",
					budgetCode: "",
					applyName: "",
					applyDept: "",
					applyType: "",
					budgetSum: "",
					budgetSum2: "",
					changeAmount: "",
					remarks: "",
					fileId: ""
				},
				itemValueList: [],
				operateType: ""
			},

			rules: {
				applyData: {
					budgetSum: [
						{ required: true, message: "请输入预算总金额", trigger: "blur" },
						{ validator: doubleValidate, trigger: "blur" }
					],
					budgetSum2: [
						{ required: true, message: "请输入预算总金额", trigger: "blur" },
						{ validator: doubleValidate, trigger: "blur" }
					],
					changeAmount: [
						{ required: true, message: "请输入预算总金额", trigger: "blur" },
						{ validator: doubleValidate, trigger: "blur" }
					],
					remarks: [
						{ required: true, message: "请输入备注", trigger: "blur" },
						{
							min: 0,
							max: 100,
							message: "长度在 0 到 100 个字符",
							trigger: "blur"
						}
					]
				}
			}
		};
	},

	computed: {
		applyDept2: function() {
			let types = getDict("budget_department");
			let pv = this.form.applyData.applyDept;
			if (pv && types.length > 0) {
				const pts = types.filter(t => t.value == pv);
				return pts ? pts[0].label : "";
			}
			return "";
		},

		applyType2: function() {
			let types = getDict("budget_type");
			let pv = this.form.applyData.applyType;
			if (pv && types.length > 0) {
				const pts = types.filter(t => t.value == pv);
				return pts ? pts[0].label : "";
			}
			return "";
		}
	},

	beforeMount() {
		this.parameterId = this.$route.query.parameterId;
		this.fileId = this.$route.query.fileId;
		this.applyFileId = this.$route.query.applyFileId;
		this.amendFileId = this.$route.query.amendFileId;
		this.applyFileId2 = this.$route.query.applyFileId2;
		this.amendFileId2 = this.$route.query.amendFileId2;

		const loading = this.$loading({
			lock: true,
			text: "数据加载中"
		});
		getObj(this.$route.query.parameterId)
			.then(respData => {
				this.$refs["add-form"].resetFields();
				this.form.applyData = respData.data.data;
				this.initItem(this.form.applyData.parameterId);

				this.initEditList(this.form.applyData.parameterId);

				loading.close();
			})
			.catch(e => {
				loading.close();
				this.$message({
					type: "error",
					message: "数据获取失败!"
				});
			});
	},
	methods: {
		// 科目
		initItem() {
			getParameterItem2(this.form.applyData.parameterId).then(rep => {
				let rspD = rep.data.data;
				rspD &&
					(this.form.itemValueList = rspD.map((item, index) => {
						return {
							...item,
							isNead: "1",
							sortNum: index + 1,
							children: item.children
								? item.children.map(it => ({ ...it, isNead: "1" }))
								: item.children
						};
					}));
			});
		},

		// 编辑历史记录
		initEditList() {
			getEditHis(this.form.applyData.parameterId).then(rep => {
				let rspD = rep.data.data;
				if (rspD) {
					rspD = rspD.map((rs, index) => {
						// rs['sortNum'] = index + 1
						return rs;
					});
				}
				this.editList = rspD;
			});
		},

		// 取消
		cancel() {
			this.closeNowRouter();
		},

		// 保存并汇总
		commit2() {
			this.form.operateType = "4";
			this.checkWillBe() &&
				this.$refs["add-form"].validate(valid => {
					valid && this.$refs.fileUpload.submit();
				});
		},
		sendFormData(val) {
			//this.loadAction('请稍等...')

			if (val && this.isEdit) {
				//this.form.applyData.fileId = val
				this.busId = val;
			}
			this.form.applyData.fileId = this.$route.query.fileId;
			updateBudgetParameter2(this.form)
				.then(rep => {
					this.success_message("修改成功");
					//this.loadClose()
					this.closeNowRouter();
				})
				.catch(e => {
					this.errormessage("修改失败");
					//this.loadClose()
				});
		},

		success_message(msg) {
			this.$message({
				type: "success",
				message: msg
			});
		},

		errormessage(msg) {
			this.$message({
				type: "error",
				message: msg
			});
		},

		closeNowRouter() {
			//关闭当前新增页，暂时没找到好办法
			this.$store.commit("delHistoryRoute", this.$route.fullPath);
			//跳转
			this.$router.push({ name: "parameter_list" });
		},

		// 上传成功监听
		handleCompleted(data) {
			this.sendFormData(data);
		},

		onSuccess(rep, file, fileList) {
			//文件上传成功，开始保存表单
			//this.loadClose()
			if (rep.data) {
				this.sendFormData(rep.data);
			} else {
				this.err("提交失败");
			}
		},

		onError(err, file, fileList) {
			//this.loadClose()
			this.err("提交失败");
		},

		beforeUpload() {
			//this.loadAction('请稍等...')
		},

		handleClean(file) {
			this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
				.then(() => {
					delFiles(file.fileId, this.modelType).then(resp => {
						if (resp.data.code === 0) {
							this.$message({
								type: "success",
								message: "删除成功!"
							});
							//this.fileList = []
							this.fileList = this.fileList.filter(
								file => file.fileId != fileId
							);
						} else {
							this.$message({
								type: "error",
								message: "删除失败!"
							});
						}
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除"
					});
				});
		}
	}
};
